// H3 v2 版本，使用内联API处理器，无需导入单独的API文件
import { getQuery, setHeader, getRouterParam, readBody } from 'h3';

// CORS辅助函数
function setCorsHeaders(event) {
  setHeader(event, 'Access-Control-Allow-Origin', '*');
  setHeader(event, 'Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  setHeader(event, 'Access-Control-Allow-Headers', 'Content-Type, Authorization');
}

export function setupApiRoutes(app, h3App) {
  console.log('🔧 正在设置API路由...');
  console.log('🔍 App实例状态:', {
    database: !!app.database,
    proxyServer: !!app.proxyServer,
    webSocketServer: !!app.webSocketServer,
    systemProxyManager: !!app.systemProxyManager
  });

  // 使用H3 v2的链式调用方式注册路由
  h3App
    // OPTIONS请求处理（CORS预检）
    .options('/api/**', (event) => {
      setCorsHeaders(event);
      return '';
    })
    
    // 测试端点
    .get('/api/test', (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'GET'} ${event.path || event.node?.req?.url}`);
      return { message: '✅ API服务器正常运行', timestamp: Date.now() };
    })
    
    // 代理相关API
    .get('/api/proxy/status', (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'GET'} ${event.path || event.node?.req?.url}`);
      
      const proxyStatus = app.proxyServer.getStatus();
      const systemProxyStatus = app.systemProxyManager.getStatus();
      
      // 返回综合状态信息
      return {
        // 代理服务器状态
        running: proxyStatus.isRunning,
        enabled: proxyStatus.isRunning && systemProxyStatus.isProxySet, // 综合状态
        isRunning: proxyStatus.isRunning,
        httpPort: proxyStatus.httpPort,
        httpsPort: proxyStatus.httpsPort,
        interceptHttps: proxyStatus.interceptHttps,
        
        // 系统代理状态
        systemProxy: {
          isSet: systemProxyStatus.isProxySet,
          host: systemProxyStatus.proxyHost,
          port: systemProxyStatus.proxyPort
        },
        
        // 其他信息
        connections: proxyStatus.connections,
        certificates: proxyStatus.certificates,
        websocket: {
          connected: app.webSocketServer.getClientCount() > 0,
          clients: app.webSocketServer.getClientCount()
        },
        database: app.database.getStats()
      };
    })
    .post('/api/proxy/toggle', async (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'POST'} ${event.path || event.node?.req?.url}`);
      try {
        if (app.proxyServer?.isRunning) {
          await app.stopProxy();
          return { success: true, status: 'stopped' };
        } else {
          await app.startProxy();
          return { success: true, status: 'started' };
        }
      } catch (error) {
        console.error('❌ 代理切换失败:', error);
        return { success: false, error: error.message };
      }
    })
    
    // 交易记录API
    .get('/api/transactions', async (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'GET'} ${event.path || event.node?.req?.url}`);
      
      try {
        console.log('📋 开始处理transactions请求...');
        
        // 从URL中手动解析查询参数
        const url = new URL(event.node?.req?.url || '', 'http://localhost');
        const limit = parseInt(url.searchParams.get('limit')) || 100;
        const offset = parseInt(url.searchParams.get('offset')) || 0;
        
        console.log(`📋 查询参数: limit=${limit}, offset=${offset}`);
        
        // 先获取统计信息
        console.log('📋 获取统计信息...');
        const stats = app.database.getStats();
        console.log(`📋 统计信息: ${JSON.stringify(stats)}`);
        
        // 再获取交易记录
        console.log('📋 获取交易记录...');
        const transactions = app.database.getTransactions(limit, offset);
        console.log(`📋 获取到 ${transactions.length} 条交易记录`);
        
        const result = { data: transactions, total: stats.totalTransactions };
        console.log(`📋 准备返回结果: ${transactions.length} 条记录，总计 ${stats.totalTransactions} 条`);
        
        return result;
      } catch (error) {
        console.error('❌ 获取交易记录失败:', error);
        console.error('❌ 错误堆栈:', error.stack);
        return { error: error.message };
      }
    })
    .delete('/api/transactions', async (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'DELETE'} ${event.path || event.node?.req?.url}`);
      
      try {
        console.log('🗑️ 开始清空所有记录...');
        
        // 先获取当前记录数量
        const stats = app.database.getStats();
        const currentCount = stats.transactions?.totalTransactions || 0;
        
        // 清空数据库记录
        const success = app.database.clearAllRecords();
        
        if (success) {
          console.log(`✅ 已清空 ${currentCount} 条记录`);
          
          // 通过WebSocket通知所有客户端
          if (app.webSocketServer) {
            app.webSocketServer.broadcast('records_cleared', { 
              success: true, 
              deletedCount: currentCount,
              timestamp: Date.now()
            });
            console.log('📡 已广播记录清空事件');
          }
          
          return { 
            success: true, 
            message: `已清空 ${currentCount} 条记录`,
            deletedCount: currentCount
          };
        } else {
          throw new Error('数据库清空操作失败');
        }
      } catch (error) {
        console.error('❌ 清空记录失败:', error);
        return { success: false, error: error.message };
      }
    })
    .get('/api/transactions/:id', (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'GET'} ${event.path || event.node?.req?.url}`);
      const id = event.context?.params?.id || getRouterParam(event, 'id');
      if (!id) {
        return { error: '缺少交易ID' };
      }
      
      const transaction = app.database.getTransaction(id);
      if (!transaction) {
        return { error: '交易记录不存在' };
      }
      
      return transaction;
    })
    
    // 规则管理API
    .get('/api/rules', (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'GET'} ${event.path || event.node?.req?.url}`);
      try {
        const rules = app.database.getRules();
        return { data: rules };
      } catch (error) {
        console.error('❌ 获取规则失败:', error);
        return { error: error.message };
      }
    })
    .get('/api/rules/:id', (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'GET'} ${event.path || event.node?.req?.url}`);
      const id = event.context?.params?.id || getRouterParam(event, 'id');
      if (!id) {
        return { error: '缺少规则ID' };
      }
      
      try {
        const rules = app.database.getRules();
        const rule = rules.find(r => r.id === id);
        if (!rule) {
          return { error: '规则不存在' };
        }
        return rule;
      } catch (error) {
        console.error('❌ 获取规则失败:', error);
        return { error: error.message };
      }
    })
    .post('/api/rules', async (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'POST'} ${event.path || event.node?.req?.url}`);
      try {
        const body = await readBody(event);
        console.log('📝 创建规则:', body);
        
        // 生成规则ID和时间戳
        const rule = {
          id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
          name: body.name,
          description: body.description || '',
          enabled: body.enabled !== false,
          conditions: body.conditions || [],
          actions: body.actions || [],
          createdAt: Date.now(),
          updatedAt: Date.now()
        };
        
        app.database.saveRule(rule);
        console.log('✅ 规则创建成功:', rule.id);
        
        return { success: true, data: rule };
      } catch (error) {
        console.error('❌ 创建规则失败:', error);
        return { success: false, error: error.message };
      }
    })
    .put('/api/rules/:id', async (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'PUT'} ${event.path || event.node?.req?.url}`);
      const id = event.context?.params?.id || getRouterParam(event, 'id');
      if (!id) {
        return { error: '缺少规则ID' };
      }
      
      try {
        const body = await readBody(event);
        console.log('📝 更新规则:', id, body);
        
        // 获取现有规则
        const rules = app.database.getRules();
        const existingRule = rules.find(r => r.id === id);
        if (!existingRule) {
          return { success: false, error: '规则不存在' };
        }
        
        // 更新规则
        const updatedRule = {
          ...existingRule,
          ...body,
          id: id, // 保持ID不变
          updatedAt: Date.now()
        };
        
        app.database.saveRule(updatedRule);
        console.log('✅ 规则更新成功:', id);
        
        return { success: true, data: updatedRule };
      } catch (error) {
        console.error('❌ 更新规则失败:', error);
        return { success: false, error: error.message };
      }
    })
    .delete('/api/rules/:id', (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'DELETE'} ${event.path || event.node?.req?.url}`);
      const id = event.context?.params?.id || getRouterParam(event, 'id');
      if (!id) {
        return { error: '缺少规则ID' };
      }
      
      try {
        app.database.deleteRule(id);
        console.log('✅ 规则删除成功:', id);
        
        return { success: true };
      } catch (error) {
        console.error('❌ 删除规则失败:', error);
        return { success: false, error: error.message };
      }
    })
    
    // 统计和健康检查API
    .get('/api/stats', (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'GET'} ${event.path || event.node?.req?.url}`);
      return app.database.getStats();
    })
    .get('/api/health', (event) => {
      setCorsHeaders(event);
      console.log(`🌐 收到请求: ${event.method || 'GET'} ${event.path || event.node?.req?.url}`);
      return {
        status: 'ok',
        timestamp: Date.now(),
        uptime: Date.now() - (app.startTime || Date.now()),
        services: {
          database: !!app.database,
          proxy: !!app.proxyServer?.isRunning,
          websocket: !!app.webSocketServer
        }
      };
    });

  console.log('✅ API路由设置完成');
  console.log('📋 可用的API端点:');
  console.log('   GET  /api/test - 测试端点');
  console.log('   GET  /api/proxy/status - 代理状态');
  console.log('   POST /api/proxy/toggle - 代理切换');
  console.log('   GET  /api/transactions - 获取交易记录');
  console.log('   DELETE /api/transactions - 清空所有记录');
  console.log('   GET  /api/transactions/:id - 获取单个交易');
  console.log('   GET  /api/rules - 获取规则列表');
  console.log('   GET  /api/rules/:id - 获取单个规则');
  console.log('   POST /api/rules - 创建规则');
  console.log('   PUT  /api/rules/:id - 更新规则');
  console.log('   DELETE /api/rules/:id - 删除规则');
  console.log('   GET  /api/stats - 统计信息');
  console.log('   GET  /api/health - 健康检查');
} 